package com.wudl.core

import org.apache.spark.broadcast.Broadcast
import org.apache.spark.{SparkConf, SparkContext}

import scala.collection.mutable

/**
 *
 * @author wudl
 * @create 2021/6/17 17:51
 * @description
 */
object BroadcastRDD {
  def main(args: Array[String]): Unit = {

    val sparkConf = new SparkConf().setMaster("local[1]").setAppName("BroadcaseRdd")
    val sc = new SparkContext(sparkConf)

    val dataRdd = sc.makeRDD(List(("a", 1), ("b", 2), ("c", 3), ("d", 4)), 4)
    val list = List(("a", 4), ("b", 5), ("c", 6), ("d", 7))

    // 声明广播变量
    val broadcast: Broadcast[List[(String, Int)]] = sc.broadcast(list)

    val result = dataRdd.map {
      case (key, num) => {
        var numb2 = 0
        // 使用广播变量
        for ((k, v) <- broadcast.value) {
          if (k == key) {
            numb2 = v
          }
        }
        (key, (num, numb2))
      }
    }
    result.foreach(println)
    sc.stop()
  }

}
